import os
import uuid
from fastapi import FastAPI, File, UploadFile, Form
from fastapi.responses import JSONResponse
from typing import List
import shutil
from constants.paths import set_current_project_id, get_save_path

# 引入你的项目主流程
# 引入你的项目主流程
# from backend_processing import process_video_for_backend # 暂时注释掉，不再直接调用

# 引入 Celery 应用和任务
from celery_worker import celery_app, process_video_task

app = FastAPI()

@app.post("/process_video/")
async def process_video(
    video: UploadFile = File(...),
    languages: List[str] = Form(...)
):
    # 1. 生成项目ID并设置保存路径
    project_id = str(uuid.uuid4())
    set_current_project_id(project_id)
    save_path = get_save_path()
    print(f"开始处理，项目ID: {project_id}")
    print(f"文件将保存到: {save_path}")

    # 确保保存目录存在
    os.makedirs(save_path, exist_ok=True)

    # 将上传的文件保存到目标路径
    original_filename = os.path.basename(video.filename)
    destination_video_path = os.path.join(save_path, original_filename)
    with open(destination_video_path, "wb") as f:
        f.write(await video.read())
    print(f"已保存上传视频到: {destination_video_path}")
    
    # 2. 将任务发送到 Celery 队列
    # 注意：这里不删除临时文件，因为 Celery worker 需要访问它
    task = process_video_task.apply_async(args=[project_id, destination_video_path, languages])

    # 3. 返回任务ID，客户端可以使用此ID查询任务状态
    return JSONResponse({"status": "Task accepted", "task_id": task.id})

@app.get("/tasks/{task_id}")
async def get_task_status(task_id: str):
    """
    查询 Celery 任务的状态和结果。
    """
    task_result = celery_app.AsyncResult(task_id)
    response = {
        "task_id": task_result.id,
        "task_status": task_result.status,
        "task_result": task_result.result
    }
    return JSONResponse(response)
